# -*- coding:utf-8 -*-
'''
@author: xiaoming
@contact: lishihui0129@163.com
@time: 2017/6/29 17:04
@desc:
'''
import re
import os
import pickle
from demo.config import quhaoFile
from myUtil import telphonePattern,flagSplitPattern
from mysqlHelper import close,connectDB,insertSql

pkl_file = open(quhaoFile, 'rb')
quhaoInfo = pickle.load(pkl_file)
pkl_file.close()


def telphoneNumExtractList(string):
    res=re.findall(telphonePattern,string)
    temp=[]
    for each in res:
        # print "---------------------------"
        # print each
        # print "---------------------------"

        # 对国家码进行处理
        # eachLong=len(each)
        # countryCode=each.find('86-')
        tmp=each.replace('0086-','',1).replace('086-','',1).replace('86-','',1)

        temp.append(tmp.strip())

    return temp

def ExtractAreaCode(string):
    temp=[]
    item=string.strip()
    if len(item)==4:
        for key,value in quhaoInfo.items():
            if key in item and item in value:
                temp.append(item)
    return temp




def areaCodeProcess(string):
    '''
    :param string:
    :return:对同一行的电话号码进行区号不全
    '''
    res=telphoneNumExtractList(string)  #提取一行有多个号码的情况、号码跨行情况

    # 提取区号和号码跨行情况
    res1=ExtractAreaCode(string)

    res=res+res1
    #
    # print "=========================================="
    # print res
    # print "=========================================="


    return res

def telphoneNumExtract(string):
    '''
    :param string: 待提取对象
    :return:提取结果
    '''

    # 避免关键词中出现空格
    # string=string.replace(" ","").replace("　","").replace(" ","")

    res=areaCodeProcess(string)

    temp=[]
    for item in res:
        linshi=item.strip()
        if len(linshi)==0:
            continue
        # linshi="座机:"+item.strip()+"("+flag+")"
        temp.append(linshi)
    # return ";".join(temp)
    # print "-------------------------------"
    # print temp
    # print "-------------------------------"
    return temp

def delCountryCode(string):
    '''
    :param string:
    :return:删除国家码后的字符串
    '''
    temp=''
    if len(string)>12:
        if "+86" in string:
            temp=string.replace('+86','')
    #         strip('-| ')
        elif "+086" in string:
            temp=string.replace('+086','')
        elif "+0086" in string:
            temp=string.replace('+0086','')
        elif "0086" in string:
            temp=string.replace('0086','')
        elif "86" in string:
            temp=string.replace('86','')
        else:
            temp=string
    else:
        temp=string

    return temp.strip('-| ')




def prefixFlag(string):
    '''
    :param string: 待提取对象
    :return:前缀信息
    '''
    guodu=string
    string=string.lower()
    # print string

    if '电话' in string:
        ind=string.index('电话')
    elif '固话' in string:
        ind=string.index('固话')
    elif '座机' in string:
        ind=string.index('座机')
    elif '专线' in string:
        ind=string.index('专线')
    elif '总机' in string:
        ind=string.index('总机')
    elif '传真' in string:
        ind=string.index('传真')
    elif 'telephone' in string:
        ind=string.index('telephone')
    elif 'tel' in string:
        ind=string.index('tel')
    elif 'fax' in string:
        ind=string.index('fax')
    elif 'F' in guodu:
        ind=guodu.index('F')
    elif 'T' in guodu:
        ind=guodu.index('T')
    else:
        ind=0

    temp=string[:ind]
    # print string
    # print temp
    res=re.split(flagSplitPattern,temp)
    return res[-1].strip()

def IncludeSwitchNum(string):
    if "，分机" in string:
        return string.replace("，分机","-").replace("—","-")
    else:
        return string.replace("—","-")


def insertTelphoneTable(string):
    res=areaCodeProcess(string)

    flag=prefixFlag(string)
    #如果属性是英文则删除
    if flag.isalpha():
        flag=""
    connectDB()
    sql="insert into telphone(telphone_value,prefix) values(%s,%s)"

    for each in res:
        param=(each,flag)
        insertSql(sql,param)
    close()


if __name__=='__main__':
    workdir='.\output'
    fileList=os.listdir(workdir)
    if 'telphone.txt' in fileList:
        targetFile=os.path.join(workdir,'telphone.txt')
        res=open(targetFile).readlines()
        for line in res:
            if len(line.strip())!=0 and len(telphoneNumExtractList(line))!=0:
                line1=IncludeSwitchNum(line)
                print telphoneNumExtract(line1)
                insertTelphoneTable(line1)
            else:
                continue
    else:
        pass


    '''
    worddir='./testData'
    for each in os.listdir(worddir):
        # temp=each.decode('gbk').encode('utf-8')
        input='./Txtoutput/'+Word2Txt.getMd5(each)+".txt"
        res=open(input).readlines()

        for line in res:
            eachline=line.replace(" ","").replace("　","").replace(" ","")
            # print eachline
            if isTelphoneNumber(eachline) and len(telphoneNumExtractList(line))!=0:
                # print line
                line1=IncludeSwitchNum(line)
                print telphoneNumExtract(line1)
            else:
                continue
    '''